#include "node_ensemble.h"

NodeEnsemble::NodeEnsemble(const int index,QWidget *parent)
    :QWidget(parent)
{
    qDebug()<<"Create: Test-node";
    item = std::make_shared<NodeItemBase>("testNode");
    setIndex(index);
    initSocket(1,1);
}

NodeEnsemble::NodeEnsemble(const int index, const int type, QWidget *parent)
    :QWidget(parent)
{

}

NodeEnsemble::NodeEnsemble(const NodeEnsemble &node_ensemble, QWidget *parent)
    :QWidget(parent)
{
    this->input_number = node_ensemble.input_number;
    this->output_number = node_ensemble.output_number;
    this->input = node_ensemble.input;
    this->output = node_ensemble.output;
    this->index = node_ensemble.index;
}

void NodeEnsemble::operator=(const NodeEnsemble &node_ensemble)
{
    this->input_number = node_ensemble.input_number;
    this->output_number = node_ensemble.output_number;
    this->input = node_ensemble.input;
    this->output = node_ensemble.output;
    this->index = node_ensemble.index;
}

NodeEnsemble::~NodeEnsemble()
{
    // 即使clear()，vector所占用的内存空间依然如故，无法保证内存的回收
    // 如果需要空间动态缩小，可以考虑使用deque。如果非vector不可，可以用swap()来帮助你释放内存
    // vector<T>().swap(input);
    // 如果vector中存放的是指针，那么当vector销毁时，这些指针指向的对象不会被销毁，那么内存就不会被释放
    this->input.clear();
    this->output.clear();
    QVector<std::shared_ptr<NodeSocket>>().swap(input);
    QVector<std::shared_ptr<NodeSocket>>().swap(input);
}

void NodeEnsemble::initSocket(int number_left, int number_right)
{
    this->input_number =number_left;
    this->output_number = number_right;
    for(int i=0;i<input_number;i++){
        std::shared_ptr<NodeSocket> socket = std::make_shared<NodeSocket>(item.get());
        socket->setPos(0,i*20+34);
        socket->setIndex(i);
        socket->setType(SOCKET_INPUT);
        input.append(socket);
    }
    for(int i=0;i<output_number; i++){

        std::shared_ptr<NodeSocket> socket2 = std::make_shared<NodeSocket>(item.get());
        socket2->setPos(180,i*20+34);
        socket2->setIndex(i);
        socket2->setType(SOCKET_OUTPUT);
        output.append(socket2);

    }
}

void NodeEnsemble::setItemTitle(QString title)
{
    this->node_name = title;
    this->item->setTitle(title);
}

int NodeEnsemble::getSelectedSocketIndex()
{
    for(int i=0;i<input.length();i++){
        if(input[i]->isSocketSelected){
            return input[i]->index;
        }
    }
    return -1;
}

void NodeEnsemble::debugOutput()
{
    for(int z=0;z<input.length();z++){
        qDebug()<<"socket is"<<this->index<<" "<<input[z]->pos();
    }

    for(int z=0;z<output.length();z++){
        qDebug()<<"socket is"<<this->index<<" "<<output[z]->pos();
    }
}

